<template>
  <div class="device-container">
    <div class="header">
      <h1>设备管理</h1>
      <el-button type="primary" @click="handleAddDevice">添加设备</el-button>
    </div>

    <el-card>
      <el-table :data="deviceList" border style="width: 100%">
        <el-table-column prop="deviceId" label="设备ID" width="120"></el-table-column>
        <el-table-column prop="deviceName" label="设备名称" width="150"></el-table-column>
        <el-table-column prop="deviceType" label="设备类型" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'">
              {{ scope.row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="200"></el-table-column>
        <el-table-column prop="location" label="安装位置"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button
                type="text"
                size="small"
                @click="handleEditDevice(scope.row)"
                style="color: #409eff;"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                size="small"
                @click="handleDeleteDevice(scope.row.deviceId)"
                style="color: #f56c6c;"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 删除确认对话框 -->
    <el-dialog
        title="确认删除"
        v-model="deleteDialogVisible"
        width="30%"
    >
      <p>确定要删除该设备吗？此操作不可撤销。</p>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '../utils/request'

const deviceList = ref([])
const deleteDialogVisible = ref(false)
const currentDeviceId = ref('')

// 页面加载时获取设备列表
onMounted(() => {
  fetchDeviceList()
})

// 获取所有设备
const fetchDeviceList = async () => {
  try {
    const response = await request.post('/device/selectAll')
    if (response.code === 200) {
      deviceList.value = response.data || []
    } else {
      ElMessage.error('获取设备列表失败：' + (response.msg || '未知错误'))
    }
  } catch (error) {
    ElMessage.error('请求失败，请检查后端服务')
    console.error('设备列表接口错误：', error)
  }
}

// 处理删除设备
const handleDeleteDevice = (deviceId) => {
  currentDeviceId.value = deviceId
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    const response = await request.post('/device/delete', {
      deviceId: currentDeviceId.value
    })
    if (response.code === 200) {
      ElMessage.success('设备删除成功')
      deleteDialogVisible.value = false
      fetchDeviceList() // 重新加载列表
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    ElMessage.error('删除失败，请重试')
    console.error('删除设备错误：', error)
  }
}

// 处理添加设备（此处仅为占位，实际需实现弹窗表单）
const handleAddDevice = () => {
  ElMessage.info('添加设备功能待实现')
}

// 处理编辑设备（此处仅为占位，实际需实现弹窗表单）
const handleEditDevice = (device) => {
  ElMessage.info(`编辑设备 ${device.deviceName}`)
}
</script>

<style scoped>
.device-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>